import json
from django.core.cache import cache
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.views import View
from django_redis import get_redis_connection
import numpy as np

from apps.user.models import User
from utils.mixin import LoginRequiredMixin

from apps.goods.models import Goods, GoodsType, IndexCreatoryGoods, IndexGoodsBanner, IndexPromotion, Youhuiquan
from apps.order.models import OrderGoods


class IndexView(View):
    def get(self, request):
        # 获取所有的商品种类信息
        types = GoodsType.objects.all()
        # 获取轮播图数据
        banners = IndexGoodsBanner.objects.all().order_by('index')
        # 获取活动数据
        promotions = IndexPromotion.objects.all().order_by('index')
        # 获取分类对应的首页数据
        for type in types:
            # 获取首页分类的文字信息
            title_banner = IndexCreatoryGoods.objects.filter(type=type, display_mode=0).order_by('index')
            # 获取首页分类的图片信息
            image_banner = IndexCreatoryGoods.objects.filter(type=type).order_by('index')

            type.title_banners = title_banner
            type.image_banners = image_banner
        index_cache = {"types": types, "banners": banners, "promotions": promotions}
        # 设置缓存
        cache.set('static_index_data', index_cache, 3600)  # 1小时过期

        # 获取当前用户购物车数量
        if request.user.is_authenticated:
            redis_conn = get_redis_connection('default')  # 连接redis
            user_id = request.user.id
            cart_len = redis_conn.hlen(f'cart_{user_id}')
            index_cache.update(cart_len=cart_len)  # 向 index_cache字典中添加或更新cart_len字段

        return render(request, 'index.html', index_cache)


class GoodDetailView(View):
    def get(self, request, good_id):
        try:
            # 获取当前商品的信息
            goods = Goods.objects.get(id=good_id)
        except Goods.DoesNotExist:
            return redirect('')

            # 获取所有商品种类信息
        types = GoodsType.objects.all()
        # 获取当前分类商品新品推荐  两条数据
        new_products = Goods.objects.filter(type=goods.type).order_by('-create_time')[:2]
        # 获取当前商品的其他规格商品信息
        # 获取商品评论信息
        order_goods = OrderGoods.objects.filter(goods_sku=good_id).exclude(comment='')

        data = {'goods': goods, 'types': types, 'new_products': new_products, 'order_goods': order_goods}

        if request.user.is_authenticated:
            redis_conn = get_redis_connection('default')
            user_id = request.user.id
            cart_len = redis_conn.hlen(f'cart_{user_id}')
            data.update(cart_len=cart_len)

            # 添加历史浏览记录
            redis_conn.lrem('history_%d' % user_id, 0, good_id)  # 先移除掉之前存在的当前商品浏览记录，有则移除，无则不处理
            redis_conn.lpush('history_%d' % user_id, good_id)  # 往左侧插入当前商品id记录

        return render(request, 'detail.html', data)


class GoodsListView(View):
    def get(self, request, type_id, page):
        try:
            type = GoodsType.objects.get(id=type_id)
        except GoodsType.DoesNotExist:
            return redirect('/')

        # 查询所有商品分类信息
        types = GoodsType.objects.all()
        # 获取新品推荐数据
        new_products = Goods.objects.filter(type=type).order_by('-create_time')[:2]

        sort = request.GET.get('sort')
        if sort == "price":
            goods = Goods.objects.filter(type=type).order_by('price')
        elif sort == "sales":
            goods = Goods.objects.filter(type=type).order_by('-sales')
        else:
            sort = "default"
            goods = Goods.objects.filter(type=type).order_by('-id')

        good_page = Paginator(goods, 10)  # 1条数据为一个页码
        try:
            page = int(page)
        except Exception as e:
            page = 1

        if page > good_page.num_pages:
            page = 1

        goods = good_page.page(page)

        """构造页码数：返回5个页码按钮，前两个页码数，当前页码数，后两个页码数"""
        # 当总页码数小于5时，返回所有的页码数
        # 如果当前页是前3页，则显示1-5页
        # 如果当前页是后3页，则显示后5页
        # 其他情况，显示 当前页的前2页，当前页，当前页的后2页
        if good_page.num_pages < 5:
            page_range = range(1, good_page.num_pages + 1)
        elif goods.number <= 3:
            page_range = range(1, 6)
        elif good_page.num_pages - goods.number <= 3:
            page_range = range(good_page.num_pages - 4, good_page.num_pages + 1)
        else:
            page_range = range(goods.number - 2, goods.number + 3)

        data = {"type": type, "types": types, "new_products": new_products, "goods": goods, "page_range": page_range,
                "sort": sort}

        if request.user.is_authenticated:
            redis_conn = get_redis_connection('default')
            user_id = request.user.id
            cart_len = redis_conn.hlen('cart_%d' % user_id)
            data.update(cart_len=cart_len)

        return render(request, 'list.html', data)


class YouhuiquanView(LoginRequiredMixin, View):
    probabilities = [0.05, 0.15, 0.1, 0.1, 0.5, 0.1]  # 概率列表
    prizes = [{
        'id': '1',
        'price': 5,
        'name': '5元无门槛券',
    }, {
        'id': '2',
        'price': 10,
        'name': '10元无门槛券',
    }, {
        'id': '3',
        'price': 20,
        'name': '20元无门槛券',
    }, {
        'id': '4',
        'price': 50,
        'name': '50元无门槛券',
    }, {
        'id': '5',
        'name': '谢谢参与',
    }, {
        'id': '6',
        'name': '再来一次'
    }
    ]

    def get(self, request):
        user_id = request.user.id
        times = User.objects.filter(id=user_id).values('prizes_times')
        for item in times:
            time = item['prizes_times']

        prizes_json = json.dumps(self.prizes, ensure_ascii=False)
        probability = json.dumps(self.probabilities, ensure_ascii=False)

        # 将 prizes_json 传递给模板  
        return render(request, 'zhuanpan.html', {'winner_list': prizes_json, 'probability': probability, 'times': time})

    def post(self, request):
        user_id = request.user.id  # 获取 user_id 参数  
        if not user_id:
            # 如果 user_id 没有提供，可以返回一个错误响应  
            return JsonResponse({'error': 'user_id is required'}, status=400)

            # 选择奖品，返回奖品信息
        selected_prize = np.random.choice(len(self.prizes), p=self.probabilities, replace=True)

        if self.prizes[selected_prize]['name'] != '谢谢参与':
            if self.prizes[selected_prize]['name'] == '再来一次':
                User.objects.filter(id=user_id).update(prizes_times=1)
            else:
                # 根据需要创建优惠券对象
                Youhuiquan.objects.create(owner=user_id, name=self.prizes[selected_prize]['name'],
                                          price=self.prizes[selected_prize]['price'])
                User.objects.filter(id=user_id).update(prizes_times=0)
        selected_prize_index = json.dumps(selected_prize, ensure_ascii=False)

        return JsonResponse({'data': selected_prize_index})
